package com.chatplus.application.service.file.impl;

import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.entity.file.SysOssEntity;
import com.chatplus.application.domain.vo.file.UpLoadFileVo;
import com.chatplus.application.enumeration.FileChannelEnum;
import com.chatplus.application.file.FileAutoConfiguration;
import com.chatplus.application.service.file.FileService;
import com.chatplus.application.service.file.SysOssService;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.InputStream;
import java.net.URI;
@Service("fileServiceOss")
public class OssFileServiceImpl extends FileService {

    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(OssFileServiceImpl.class);
    private final SysOssService sysOssService;
    private final String contextPath;

    public OssFileServiceImpl(SysOssService sysOssService
            , FileAutoConfiguration.FileProperties fileProperties
            , ServerProperties serverProperties) {
        super(fileProperties);
        this.sysOssService = sysOssService;
        this.contextPath = serverProperties.getServlet().getContextPath();
    }

    /**
     * 上传文件远程调用SDK
     */
    @Override
    public UpLoadFileVo uploadFile(MultipartFile scrFile) {

        SysOssEntity sysOssEntity = sysOssService.upload(scrFile);
        UpLoadFileVo vo = new UpLoadFileVo(true,
                sysOssEntity.getId().toString(),
                sysOssEntity.getHashId(),
                sysOssEntity.getUrl(),
                sysOssEntity.getContentType());
        String contentType = vo.getContentType();
        String url;
        String fileUrl = fileProperties.getAccessBaseUrl();
        UriComponentsBuilder builder = UriComponentsBuilder.fromUri(URI.create(fileUrl)).replaceQuery("");
        if (contentType.startsWith("image")) {
            url = builder.replacePath(contextPath + "/api/image/{hashId}").build(vo.getHashId()).toString();
        } else {
            url = builder.replacePath(contextPath + "/api/file/{hashId}").build(vo.getHashId()).toString();
        }
        vo.setUrl(url);
        return vo;
    }
    @Override
    public InputStream getInputStream(Long id) {
        return sysOssService.getFileInputStream(id);
    }

    @Override
    public SysOssEntity getByHashId(String hashId) {
        return sysOssService.getByHashId(hashId);
    }

    @Override
    public FileChannelEnum getUploadChannel() {
        return FileChannelEnum.OSS;
    }
}
